package com.wechart.utils;

//import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//import java.util.Base64;

/**
 * Created by silenceholic on 2017/3/8.
 */
public class EncryptUtils {

//    public static String SHA256ThenBase64Encoder(final String strText) throws UnsupportedEncodingException {
//        return encryptBASE64(SHA(strText, "SHA-256"));
//    }

    /**
     * 传入文本内容，返回 SHA-256 串
     *
     * @param strText
     * @return
     */
    public static byte[] SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    /**
     * 字符串 SHA 加密
     *
     * @param strText
     * @param strType
     * @return
     */
    public static byte[] SHA(final String strText, final String strType) {
        // 返回值
        byte[] hashed = null;

        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密類型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                hashed = messageDigest.digest(strText.getBytes());
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return hashed;

    }

    public final static String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

//    /**
//     * BASE64加密
//     *
//     * @param hashed
//     * @return
//     * @throws UnsupportedEncodingException
//     * @throws Exception
//     */
//    public static String encryptBASE64(byte[] hashed) throws UnsupportedEncodingException {
//        Base64.Encoder encoder = Base64.getEncoder();
//        return encoder.encodeToString(hashed);
//    }

    public static void main(String[] args) {
        System.out.println("begin");
        System.out.println(SHA256("abcd12345"));
//        try {
////            System.out.println(SHA256ThenBase64Encoder("abcd12345"));
//        } catch (UnsupportedEncodingException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }
}
